#!/bin/bash
# vim: set ft=sh

set -eu
set -o pipefail

exec 3>&1 # make stdout available as fd 3 for the result
exec 1>&2 # redirect all output to stderr for logging

resource_dir=$(dirname $0)

source $resource_dir/common.sh

source=${1:-}
if [ -z "$source" ]; then
  echo "usage: $0 <path/to/source>"
  exit 1
fi

#cd $source

# for jq
PATH=/usr/local/bin:$PATH

TMPDIR=${TMPDIR:-/tmp}
payload=$(mktemp $TMPDIR/maven-resource-request.XXXXXX)
working=$TMPDIR/maven-resource-working && mkdir -p $working
jars_dir=$TMPDIR/jars && mkdir -p $jars_dir

cat > $payload <&0

debug=$(jq -r '.source.debug //empty' < $payload)
if [ "$debug" = "true" ]; then
  set -x
fi

release_url=$(jq -r '.source.url //empty' < $payload)
snapshot_url=$(jq -r '.source.snapshot_url //empty' < $payload)
artifact=$(jq -r '.source.artifact //empty' < $payload)
username=$(jq -r '.source.username //empty' < $payload)
password=$(jq -r '.source.password //empty' < $payload)
disable_redeploy=$(jq -r '.source.disable_redeploy //empty' < $payload)
skip_cert_check=$(jq -r '.source.skip_cert_check //empty' < $payload)
repository_cert=$(jq -r '.source.repository_cert //empty' < $payload)

file=$(jq -r '.params.file //empty' < $payload)
pom_file=$(jq -r '.params.pom_file //empty' < $payload)
version_file=$(jq -r '.params.version_file //empty' < $payload)

zip_builds=$(jq -r '.params.app //empty' < $payload)
file_in_builds=$(jq -r '.params.app_file //empty' < $payload)

sourceMavenOpts=$(jq -r '.source.maven_opts //empty' < $payload)
sourceMavenConfig=$(jq -r '.source.maven_config //empty' < $payload)
paramsMavenOpts=$(jq -r '.params.maven_opts //empty' < $payload)
paramsMavenConfig=$(jq -r '.params.maven_config //empty' < $payload)

# Allow overriding the source config values
export MAVEN_OPTS=${paramsMavenOpts:-$sourceMavenOpts}
export MAVEN_CONFIG=${paramsMavenConfig:-$sourceMavenConfig}
export MAVEN_BASEDIR=$resource_dir

# Use ours if user didn't specify
[ -z "$MAVEN_CONFIG" ] && MAVEN_CONFIG="-s $resource_dir/.mvn/settings.xml"

# groupId:artifactId:type[:classifier]
groupId=$(get_group_id $artifact)
artifactId=$(get_artifact_id $artifact)
packaging=$(get_packaging $artifact)
classifier=$(get_classifier $artifact)

# TODO: Add more error checking
if [ -z "$release_url" ] && [ -z "$snapshot_url" ]; then
  echo "[ERROR] invalid payload (must specify url or snapshot_url)"
  exit 1
fi

if [ -z "$file" ] && ( [ -z "$zip_builds" ] || [ -z "$file_in_builds" ] ); then
  echo "[ERROR] invalid payload (missing file)"
  exit 1
fi

echo "pwd"
pwd

if [ -n "$zip_builds" ] && [ -n "$file_in_builds" ]; then
    tar -zxvf "$zip_builds" -C $jars_dir
    file="$jars_dir/$file_in_builds"
fi

# transform this: build-output/your-artifact-*.jar
#      into this: build-output/your-artifact-1.0.0-rc.0.jar
file=$(ls $file)
pom_file=$(ls $pom_file)

if [ -f "$version_file" ]; then
  version=$(cat $version_file)
elif [ -f "$pom_file" ]; then
  version=$(printf 'POM_VERSION=${project.version}\n0\n' | $resource_dir/mvnw help:evaluate -f $pom_file | grep '^POM_VERSION' | cut -d = -f 2)
else
  echo "[ERROR] invalid payload (must specify version file or pom file)"
  exit 1
fi

if [ "$skip_cert_check" = "true" ]; then
  MAVEN_OPTS="$MAVEN_OPTS -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
elif [ -n "$repository_cert" ]; then
  mkdir -p $working/security
  echo "$repository_cert" > $working/security/repository.crt
  : "${JAVA_HOME:?[ERROR] JAVA_HOME not set or empty}"
  cp  $JAVA_HOME/jre/lib/security/cacerts $working/security/.
  keytool -noprompt -storepass changeit -keystore $working/security/cacerts -import -file $working/security/repository.crt -alias maven-resource-repository-CAAlias
  MAVEN_OPTS="$MAVEN_OPTS -Djavax.net.ssl.trustStore=$working/security/cacerts -Djavax.net.ssl.trustStorePassword=changeit"
fi

# test for 1.0.0-SNAPSHOT and for 1.0.0-20170328.031519-19
isSnapshot=false
[[ "$version" = *-SNAPSHOT ]] || echo "$version" | grep -oEq "[0-9]{8}\.[0-9]{6}-[0-9]{1,}" && isSnapshot=true

url=$release_url
[ -n "$snapshot_url" ] && [ "$isSnapshot" = true ] && url=$snapshot_url

if [ "$disable_redeploy" = "true" ] && [ "$isSnapshot" != true ]; then
  foundVersions=$(jq -n \
  --arg version "$version" \
  --arg url "$release_url" \
  --arg artifact "$artifact" \
  --arg username "$username" \
  --arg password "$password" \
  --arg skip_cert_check "$skip_cert_check" \
  --arg repository_cert "$repository_cert" \
  --arg debug "$debug" \
  '{
    version: {
      version: $version
    },
    source: {
      url: $url,
      artifact: $artifact,
      username: $username,
      password: $password,
      skip_cert_check: $skip_cert_check,
      repository_cert: $repository_cert,
      debug: $debug
    }
  }' | $resource_dir/check "$source" | jq -r '.[].version')

  for foundVersion in $foundVersions; do
    if [ "$version" = "$foundVersion" ]; then
      echo "[WARNING] disable_redeploy enabled: Found existing version $version in repository $release_url. Skipping deploy!"
      jq -n \
      --arg version "$version" \
      '{
        version: {version: $version}
      }' >&3
      exit 0
    fi
  done
fi

args=
args="$args -Dfile=$file"
args="$args -Durl=$url"
args="$args -DgroupId=$groupId"
args="$args -DartifactId=$artifactId"
args="$args -Dversion=$version"
args="$args -Dpackaging=$packaging"

[ -f "$pom_file" ]   && args="$args -DpomFile=$pom_file"
[ -n "$classifier" ] && args="$args -Dclassifier=$classifier"
[ -n "$username" ]   && args="$args -Drepository.username=$username";
[ -n "$password" ]   && args="$args -Drepository.password=$password";

echo $args

$resource_dir/mvnw deploy:deploy-file $args

# get the real snapshot version number
if [[ "$version" = *-SNAPSHOT ]]; then
  version=$(jq -n \
  --arg version "$version" \
  --arg release_url "$release_url" \
  --arg snapshot_url "$snapshot_url" \
  --arg artifact "$artifact" \
  --arg username "$username" \
  --arg password "$password" \
  --arg skip_cert_check "$skip_cert_check" \
  --arg repository_cert "$repository_cert" \
  --arg debug "$debug" \
  '{
    version: {
      version: $version
    },
    source: {
      url: $release_url,
      snapshot_url: $snapshot_url,
      artifact: $artifact,
      username: $username,
      password: $password,
      skip_cert_check: $skip_cert_check,
      repository_cert: $repository_cert,
      debug: $debug
    }
  }' | $resource_dir/check "$source" | jq -r '.[].version')
fi

jq -n \
--arg version "$version" \
'{
  version: {version: $version}
}' >&3
